package ar.edu.unlp.info.tesis.controladores;

import javax.servlet.http.HttpSession;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.savedrequest.DefaultSavedRequest;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import ar.edu.unlp.info.tesis.database.service.GenericService;
import ar.edu.unlp.info.tesis.domain.Usuario;
import ar.edu.unlp.info.tesis.misc.ContextoAplicacion;

@Controller
@RequestMapping("/")
@SessionAttributes("id")
@Transactional
public class AccessController {
	
	@RequestMapping
	public String getIndexPage(Model m, HttpSession session)
	{
		if(session.getAttribute("contextoAplicacion") != null)
		{
			m.addAttribute("menuSeleccionado", "Home");
			return "home";
		}
		else 
		{
			m.addAttribute("nombre_seccion", "Acceso al sistema");
			m.addAttribute("icono_seccion", "accesosistema.png");
			return "login";
		}
	}
	
	@RequestMapping(value="home")
	public String getHomePage(Model m, HttpSession session)
	{
		Usuario u = (Usuario) GenericService.getService(Usuario.class).findByProperty("username", SecurityContextHolder.getContext().getAuthentication().getName());
				
		ContextoAplicacion ca = new ContextoAplicacion();
		ca.setUsuario(u);
		
		session.setAttribute("contextoAplicacion", ca);
		
		SavedRequest savedRequest = (SavedRequest) session.getAttribute("SPRING_SECURITY_SAVED_REQUEST");
		if(savedRequest != null)
			return "redirect:" + ((DefaultSavedRequest)savedRequest).getServletPath();
		
		return "redirect:/";
	}

	@RequestMapping("login")
	public String login(Model model, @RequestParam(required=false) String message) 
	{
		model.addAttribute("message", message);
		model.addAttribute("nombre_seccion", "Acceso al sistema");
		model.addAttribute("icono_seccion", "accesosistema.png");
		return "login";
	}
	
	@RequestMapping(value = "loginDenied", method = RequestMethod.GET)
 	public String denied(Model m) 
	{
		m.addAttribute("nombre_seccion", "Acceso Denegado");
		m.addAttribute("icono_seccion", "btn_restringido.png");
		return "denied";
	}
	
	@RequestMapping(value = "loginFailure")
 	public String loginFailure()
	{
		return "redirect:/login";
	}
	
	@RequestMapping(value = "logoutSuccess")
 	public String logoutSuccess()
	{
		return "redirect:/login";
	}
}
